import { createSlice } from '@reduxjs/toolkit'
import axios from 'axios'

const foodsListStore = createSlice({
  name: 'foodList',
  initialState: {
    foodList: [], // 页面所有食物数据
    cartList: [] // 购物车列表
  },
  reducers: {
    // 同步修改数据的方法
    setFoodList(state, action) {
      state.foodList = action.payload
    },
    setCartList(state, action) {
      state.cartList = action.payload
    }
  }
})

// ,解构出action对象的函数
const { setFoodList, setCartList } = foodsListStore.actions

// 异步请求
const getFoodsList = () => {
  // 这里不理解为什么传入的dispatch???
  return async (dispatch) => {
    const res = await axios.get('http://localhost:3004/takeaway')
    console.log('res', res)
    dispatch(setFoodList(res.data))
  }
}

export { getFoodsList, setCartList }

const foodsReducers = foodsListStore.reducer

export default foodsReducers
